package org.kreedx.view.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import org.kreedx.view.manager.TextManager;
import org.kreedx.view.util.DensityUtil;
import org.kreedx.view.util.ToastUtil;

public class FontView extends View {

    private Paint paint;

   //设置属性
    private int gapX = 30;
    private int gapY = 50;
    private int wordNum = 15;
    private int lineNum = 10;
    //计算属性
    private int startX = 100;
    private int startY = 50;
    private int page = 1;

    private TextManager textManager;

    String text = "1.库工程里面的assets文件夹无用，不会被打包到APK\n" +
            "2.库工程里面的AndroidManifest.xml无用，要声明Activity，必须写到主工程\n" +
            "3.当库工程文件中的资源ID和主工程中的资源ID相同时，主工程的资源ID将会覆盖掉库工程的资源ID\n" +
            "4.当主工程所引用的两个库工程中有相同的ID时，Android编译工具会选择一个优先级高的ID 进行合并到主工程，而抛弃另一个工程的ID\n" +
            "5.库工程使用的android版本不能高于调用它的主工程所使用的anroid版本.\n" +
            "6.库工程的包名，不必改变，主工程的包名，才是生成的 apk 的包名，跟库工程没关系\n" +
            "7.库工程的里面的资源id，不再是public static final int，而是public static int，没有final了。最大的影响是 你在某些点击事件，使用switch来判断R.id.xx的时候，就不行了。改为if else if 就行\n" +
            "8.在我们的库工程用到了res/values/attrs.xml，即xml自定义属性。它不作为一个库工程的时候就不会报错，而作为一个库工程的时候却报错。把 layout里面xml布局，凡是使用了attrs里面属性的头部由 xmlns:app=”http://schemas.android.com/apk/res/com.xxx.common”改为 xmlns:app=”http://schemas.android.com/apk/res-auto”\n" +
            "\n" +
            "作者：不一落叶\n" +
            "链接：https://www.jianshu.com/p/0523c682c718\n" +
            "来源：简书\n" +
            "简书著作权归作者所有，任何形式的转载都请联系作者获得授权并注明出处。";

    public FontView(Context context) {
        this(context,null);
    }

    public FontView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public FontView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        paint.setTextSize(30);
        paint.setTypeface(Typeface.MONOSPACE);


        paint.setTypeface(Typeface.createFromAsset(getContext().getAssets(),"demo.ttf"));

        DisplayMetrics metrics ;
        metrics = getContext().getResources().getDisplayMetrics();
        int width = metrics.widthPixels;


        startX = (width - wordNum *gapX)/2;
        textManager = TextManager.create(text,lineNum,wordNum);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public FontView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }


    @Override
    protected void onDraw(Canvas canvas) {

        String text = textManager.getPage(page);
        Log.e("text",text);

        int num = text.length();
        int lineIndex = 0;
        int worldIndex = 0;
        for (int j = 0; j < num; j++) {
            String msg = text.substring(j ,j+1);
            if(!msg.equals("\n")){
                canvas.drawText(msg,startX+gapX*worldIndex,startY+gapY*lineIndex,paint);
                worldIndex ++;
                if(worldIndex >= wordNum){
                    worldIndex = 0;
                    lineIndex ++;
                }
            }else {
                worldIndex = 0;
                lineIndex ++;
            }
        }

        text = textManager.getPage(page+1);

        num = text.length();
        lineIndex = 0;
        worldIndex = 0;
        for (int j = 0; j < num; j++) {
            String msg = text.substring(j ,j+1);
            if(!msg.equals("\n")){
                canvas.drawText(msg,startX+gapX*worldIndex,startY+lineNum*gapY+gapY*lineIndex,paint);
                worldIndex ++;
                if(worldIndex >= wordNum){
                    worldIndex = 0;
                    lineIndex ++;
                }
            }else {
                worldIndex = 0;
                lineIndex ++;
            }
        }

    }

    private int lastX,lastY;
    private boolean isMove = false;
    @Override
    public boolean onTouchEvent(MotionEvent event) {


        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 记录触摸点坐标
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                isMove = true;
                // 计算偏移量
                int offsetX = x - lastX;
                int offsetY = y - lastY;
                // 在当前left、top、right、bottom的基础上加上偏移量
                //layout(getLeft() + offsetX, getTop() , getRight() + offsetX, getBottom());
//                        offsetLeftAndRight(offsetX);
//                        offsetTopAndBottom(offsetY);


                startY += DensityUtil.px2dp(offsetY)/10;
                if(startY > 50 + lineNum*gapY){
                    goPrev();
                    startY -= lineNum*gapY;
                }else if(startY < 50 - lineNum*gapY){
                    goNext();
                    startY += lineNum*gapY;
                }
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                if(isMove){
                    isMove = false;
                    break;
                }
                DisplayMetrics metrics ;
                metrics = getContext().getResources().getDisplayMetrics();
                int width = metrics.widthPixels;

                performClick();
                startY = 50;
                if(event.getX() > width/2){
                    goNext();
                }else {
                    goPrev();
                }

                invalidate();
                break;
        }
        return true;
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);

        if (specMode == MeasureSpec.AT_MOST) {
            specSize = lineNum * gapY + startY * 2;
        }

        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),specSize);
    }

    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l, t, r, b);
    }

    public void setText(String text) {
        this.text = text;
        init();
        invalidate();
    }

    private void goPrev(){
        if(1 <= page-1){
            page--;
        }else {
            ToastUtil.show("最前了");
        }
    }

    private void goNext(){
        if(textManager.getPageNum()>= page+1){
            page++;
        }else {
            ToastUtil.show("最后了");
        }
    }
}
